package com.kepler.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.kepler.pojo.Role;
import com.kepler.pojo.User;
import com.kepler.service.role.RoleService;
import com.kepler.service.role.RoleServiceImpl;
import com.kepler.service.user.UserService;
import com.kepler.service.user.UserServiceImpl;
import com.kepler.util.Constant;
import com.kepler.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.SimpleFormatter;

/**
 * @author lenovo
 * Servlet复用
 */
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter(Constant.METHOD);
        if (Constant.SAVE_PASSWORD.equals(method)){
            this.updatePassword(req, resp);
        } else if (Constant.DEAL_OLD_PASSWORD.equals(method)){
            this.pwdmodify(req, resp);
        } else if (Constant.USER_MANGER.equals(method)){
            this.query(req, resp);
        } else if (Constant.INSERT_USER.equals(method)){
            this.add(req, resp);
        } else if (Constant.GET_ROLE_LIST.equals(method)){
            this.getRoleList(req, resp);
        } else if (Constant.USER_CODE_EXIST.equals(method)){
            this.userCodeExist(req, resp);
        } else if (Constant.DELETE_USER.equals(method)){
            try {
                this.deleteUser(req, resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } else if (Constant.MODIFY_USER.equals(method)){
            try {
                this.getUserById(req, resp, "usermodify.jsp");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } else if (Constant.MODIFY_EXE.equals(method)){
            try {
                this.modify(req, resp);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        } else if (Constant.VIEW_PAGE.equals(method)) {
            try {
                this.getUserById(req, resp, "userview.jsp");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 修改密码方法
     */
    public void updatePassword(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        String newPassword = req.getParameter("newpassword");
        boolean flag = false;

        if (o != null && !StringUtils.isNullOrEmpty(newPassword)){
            // 创建用户服务实例
            UserService userService = new UserServiceImpl();
            // 调用服务的修改密码方法
            flag = userService.updatePassword(((User) o).getId(), newPassword);
            if (flag) {
                req.setAttribute(Constant.MESSAGE, "密码修改成功，请重新登录");
                req.getSession().removeAttribute(Constant.USER_SESSION);
            } else {
                req.setAttribute(Constant.MESSAGE, "密码修改失败，请重新尝试");
            }
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理旧密码方法
     * 注意使用 Session
     */
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        String oldPassword = req.getParameter("oldpassword");

        Map<String, String> resultMap = new HashMap<String, String>();

        if (o == null){
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldPassword)){
            resultMap.put("result", "error");
        } else {
            if (((User)o).getUserPassword().equals(oldPassword)){
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户管理方法
     */
    public void query(HttpServletRequest req, HttpServletResponse resp){
        // 查询用户列表,从前端获取数据
        // 需要查询的名字
        String queryName = req.getParameter("queryname");
        // 需要查询的用户角色
        String temp = req.getParameter("queryUserRole");
        // 获取当前页面
        String pageIndex = req.getParameter("pageIndex");

        int queryUserRole = 0;
        // 获取用户列表
        UserService userService = new UserServiceImpl();
        List<User> userList = null;

        // 第一次走这个请求，一定是第一页，页面大小固定的
        int pageSize = 5;
        int currentPageNo = 1;

        if (queryName == null) {
            queryName = "";
        }
        if (!StringUtils.isNullOrEmpty(temp)){
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        // 获取用户的总数 （ 分页：上一页，下一页的情况 ）
        int totalCount = userService.getUserCount(queryName, queryUserRole);
        // 总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();

        // 控制首页和尾页
        // 首页控制，如果当前页数小于 1，让他等于 1
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        // 获取用户列表展示
        userList = userService.getUserList(queryName, queryUserRole, currentPageNo, pageSize);
        req.setAttribute("userList", userList);

        RoleService roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);

        try {
            req.getRequestDispatcher("userlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 增加用户
     */
    public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        User user = new User();
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setPhone(phone);
        user.setAddress(address);
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setGender(Integer.parseInt(gender));
        user.setUserRole(Integer.parseInt(userRole));
        user.setCreationDate(new Date());
        user.setCreatedBy(((User)req.getSession().getAttribute(Constant.USER_SESSION)).getUserRole());

        UserService userService = new UserServiceImpl();
        if (userService.addUser(user)){
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("useradd.jsp").forward(req, resp);
        }
    }

    /**
     * 获取用户身份
     */
    public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Role> roleList = new ArrayList<Role>();
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();
        // 将 roleList 转化成 JSON 对象输出
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(roleList));
        writer.flush();
        writer.close();
    }

    /**
     * 判断用户的编号是否在数据库中已经存在
     */
    public void userCodeExist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userCode = req.getParameter("userCode");
        System.out.println(userCode);
        UserService userService = new UserServiceImpl();
        HashMap<String, String> resultMap = new HashMap<String, String>();

        if (StringUtils.isNullOrEmpty(userCode)) {
            resultMap.put(Constant.USER_CODE, "exist");
        } else {
            if (userService.selectUserCodeExist(userCode)) {
                resultMap.put(Constant.USER_CODE, "exist");
            } else {
                resultMap.put(Constant.USER_CODE, "notExist");
            }
        }
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    /**
     * 删除用户
     */
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String uid = req.getParameter("uid");
        int delId = 0;
        try {
            delId = Integer.parseInt(uid);
        } catch (Exception e){
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();

        if (delId <= 0){
            resultMap.put(Constant.DELETE_RESULT, "notexist");
        } else {
            UserService userService = new UserServiceImpl();
            if (userService.deleteUser(delId) > 0){
                resultMap.put(Constant.DELETE_RESULT, "true");
            } else {
                resultMap.put(Constant.DELETE_RESULT, "false");
            }
        }
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }

    /**
     * 修改用户
     */
    public void modify(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {
        String uid = req.getParameter("uid");
        Integer modifyBy = ((User) req.getSession().getAttribute(Constant.USER_SESSION)).getId();
        String userName = req.getParameter("userName");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");

        int modifyId = 0;
        int modifyGender = 1;
        int modifyUserRole = 3;
        User user = new User();
        try {
            modifyId = Integer.parseInt(uid);
            modifyGender = Integer.parseInt(gender);
            modifyUserRole = Integer.parseInt(userRole);
        } catch (Exception e){
            modifyId = 0;
            modifyGender = 1;
            modifyUserRole = 3;
            e.printStackTrace();
        }
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setId(modifyId);
        user.setUserName(userName);
        user.setGender(modifyGender);
        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(modifyUserRole);
        user.setModifyBy(modifyBy);
        user.setModifyDate(new Date());

        UserService userService = new UserServiceImpl();
        if (userService.modify(user)){
            resp.sendRedirect(req.getContextPath() + "/jsp/user.do?method=query");
        } else {
            req.getRequestDispatcher("usermodify.jsp").forward(req, resp);
        }
    }

    /**
     * 通过用户 id 获取用户信息，并加载页面
     */
    public void getUserById(HttpServletRequest req, HttpServletResponse resp, String url) throws SQLException, ServletException, IOException {
        String uid = req.getParameter("uid");
        if (!StringUtils.isNullOrEmpty(uid)){
            UserService userService = new UserServiceImpl();
            User user = userService.getUserById(Integer.parseInt(uid));
            req.setAttribute("user", user);
            System.out.println(user.toString());
            req.getRequestDispatcher(url).forward(req, resp);
        }
    }
}
